package org.jeecg.modules.clue.job;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.clue.service.IClueRecordTaskService;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;

@Slf4j
@Component
@DisallowConcurrentExecution
public class ClueTaskPushListener implements Job {

    /**
     * 若参数变量名修改 QuartzJobController中也需对应修改
     */
    private String parameter;

    public void setParameter(String parameter) {
        this.parameter = parameter;
    }

    public static String Topic = "ClueTaskPush";

    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    IClueRecordTaskService clueRecordTaskService;
    @Resource(name = "TaskPushThreadPool")
    ThreadPoolTaskExecutor taskPushThreadPool;


    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info("ClueTaskPushListener 定时任务");
        ZSetOperations<String, String> opsForZSet = stringRedisTemplate.opsForZSet();
        Set<String> taskIds = opsForZSet.rangeByScore(Topic, 0, System.currentTimeMillis());
        if (CollectionUtil.isEmpty(taskIds)) {
            return;
        }
        log.info("taskIds {} CONSUME {}", Topic, taskIds);
        for (String taskId : taskIds) {
            taskPushThreadPool.execute(() -> {
                clueRecordTaskService.pushTask(taskId);
                //   删除队列value
                opsForZSet.remove(Topic, taskId);
            });

        }


    }
}
